from flask import Flask, current_app, make_response
from flask_restful import Resource, Api, representations
from flask_restful.utils import PY3
from json import dumps

app = Flask(__name__)
api = Api(app)

"""
Flask-RESTful的Api对象提供了一个representation的装饰器，允许定制返回数据的呈现格式
"""

@api.representations('application/json')
def handle_json(code, data, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    # 此处为自己添加***************
    if 'message' not in data:
        data = {
            'message': 'OK',
            'data': data
        }
    # **************************

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp

class User1Resource(Resource):
    def get(self):
        return {"name":'lisi'}



api.add_resource(User1Resource, '/user1')


if __name__ == '__main__':
    app.run(debug=True)


